package yxy.game.pm2.command.wuchao;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.WuchaoMessage;
import yxy.game.pm2.module.player.PlayerHandle;
import yxy.game.pm2.module.wuchao.RankWuchao;

import java.util.Collection;

/** 乌巢 乌巢排行榜 */
@MessageType(proto = Command.WuchaoRank, classtype = WuchaoMessage.WuchaoRankRequest.class)
public class CMD_WuchaoRank extends Command<WuchaoMessage.WuchaoRankRequest> {

	@Override
	public void execute(MessageSource messageSource, WuchaoMessage.WuchaoRankRequest request) {
		String playerCode = messageSource.getTag();

		WuchaoMessage.WuchaoRankResponse.Builder response = WuchaoMessage.WuchaoRankResponse.newBuilder();

		RankWuchao rankWuchao = RankWuchao.getRank(playerCode);

		try {
			PlayerHandle playerHandle = new PlayerHandle();

			Collection<RankEntry> top = rankWuchao.top(rankWuchao.topSize());
			int rank = 0;
			for (RankEntry entry : top) {
				String pCode = entry.getKey();
				int value = entry.getValue().intValue();
				int stage = value / 100;
				int explore = value % 100;

				WuchaoMessage.RankWuchao.Builder builder = WuchaoMessage.RankWuchao.newBuilder();
				builder.setRank(++rank);
				builder.setPlayerInfo(playerHandle.playerSimpleInfo(pCode));
				builder.setFloor(stage);
				builder.setExplore(explore);
				response.addRank(builder);
			}

			{
				int playerRank = 0;
				int stage = 0;
				int explore = 0;
				RankEntry entry = rankWuchao.get(playerCode);
				if (entry != null) {
					playerRank = rankWuchao.rank(playerCode);
					int value = entry.getValue().intValue();
					stage = value / 100;
					explore = value % 100;
				}

				WuchaoMessage.RankWuchao.Builder builder = WuchaoMessage.RankWuchao.newBuilder();
				builder.setRank(playerRank);
				builder.setPlayerInfo(playerHandle.playerSimpleInfo(playerCode));
				builder.setFloor(stage);
				builder.setExplore(explore);
				response.setMy(builder);
			}

			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}
	}

	private void send(MessageSource messageSource, WuchaoMessage.WuchaoRankResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}